/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-11 17:52:20
 * @Last modified by:   ls-mac
 * @Last modified time: 2020-03-12 12:56:55
 */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Alert,
  AutoComplete,
  Row,
  Col,
  Card,
  Checkbox,
  Form,
  Input,
  List,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Popover,
  Popconfirm,
  TimePicker,
  Tag,
  Table,
  Modal,
  message,
  Badge,
  Divider,
  Upload,
} from 'antd';
import moment from 'moment';
import SimpleTable from 'components/SimpleTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './enterprise.less';

const FormItem = Form.Item;

const { Option } = Select;

const { RangePicker } = DatePicker;

@connect(
  ({
    companyStorePage,
    dict,
    contractList,
    enterpriseList,
    employeeList,
    extraItemList,
    institutionList,
    loading,
  }) => ({
    companyStorePage,
    enterpriseList,
    dict,
    contractList,
    employeeList,
    extraItemList,
    institutionList,
    loading: loading.models.companyStorePage,
  })
)
@Form.create()
export default class TableList extends PureComponent {
  uploadProps = {
    name: 'file',
    action: 'https://service-api.lisonhealth.com/upload',
    showUploadList: false,
    headers: {
      Authorization: localStorage.getItem('authorization-token'),
    },
    listType: 'picture-card',
    onChange: info => {
      const { dispatch, form } = this.props;
      if (info.file.status === 'uploading') {
        this.setState({ stateloading: true });
        return;
      }
      if (info.file.status === 'done') {
        const { success } = info.file.response;
        if (success) {
          message.success(`导入成功.`);
          this.getBase64(info.file.originFileObj, imageUrl =>
            this.setState({
              imageUrl,
              stateloading: false,
            })
          );

          const {
            file: {
              response: { data },
            },
          } = info;

          this.setState({
            attachmentUrl: data,
          });
          form.setFieldsValue({ attachmentUrl: data });
        } else {
          message.success(`导入失败.`);
        }
      } else if (info.file.status === 'error') {
        message.error(`上传文件失败.`);
      }
    },
  };

  state = {
    dataSource: [], // 企业名称 数据源
    result: [], // 企业名称 自动匹配结果
    companyId: '', // 企业id
    contractId: '', // 合同id
    contarctValue: '',
    type: 'add',
    imageUrl: '',
    stateLoading: '',
    attachmentUrl: '',
  };

  componentDidMount() {
    const {
      dispatch,
      location: { query },
    } = this.props;

    let companyId = '';
    let id = '';
    // 查询员工详情
    if (query) {
      ({ companyId, id } = query);
      dispatch({
        type: 'extraItemList/extraItemDetail',
        payload: {
          id,
        },
      });
      // dispatch({
      //   type: 'enterpriseList/positionList',
      //   payload: {
      //     companyId,
      //   },
      // });

      dispatch({
        type: 'contractList/getList',
        payload: { companyId },
      });

      this.setState({
        type: 'edit',
      });
    }

    // 查询公司
    dispatch({
      type: 'companyStorePage/companyList',
      payload: {
        name: '',
      },
      callback: res => {
        const newList = res.data.map(v => {
          return <Option value={v.id}>{v.name}</Option>;
        });
        this.setState({
          dataSource: newList,
          result: newList,
        });
      },
    });

    // 查询门店
    dispatch({
      type: 'dict/dictStoreList',
      payload: {
        cityId: '',
        institutionId: '',
        name: '',
        provinceId: '',
      },
    });

    // 查询省份
    dispatch({
      type: 'dict/dictProvinceList',
      payload: {},
    });

    // 查询套餐加项
    dispatch({
      type: 'extraItemList/getExtraItemList',
      payload: {
        packageId: '',
      },
    });

    // 查询门店特性
    dispatch({
      type: 'dict/dictList',
      payload: { type: 'STORE_FEATURE' },
    });

    // // 适用机构
    // dispatch({
    //   type: 'institutionList/dictInstitutionList',
    //   payload: '',
    // });

    // 清除
    dispatch({
      type: 'extraItemList/clearExtraItemList',
    });
  }

  onSelect = v => {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'contractList/getList',
      payload: { companyId: v },
    });

    this.setState(
      {
        companyId: v,
        contarctValue: '',
      },
      () => {
        dispatch({
          type: 'enterpriseList/positionList',
          payload: {
            companyId: v,
          },
        });
      }
    );

    form.setFieldsValue({ companyId: v });
  };

  onChangeH = (v, t) => {
    if (!t) {
      return;
    }
    const {
      props: { children },
    } = t;
    this.setState({
      contractId: v,
      contarctValue: children,
    });
  };

  // 查询公司
  handleSearch = value => {
    const { dataSource } = this.state;
    const newList = dataSource.filter(v => v.props.children.indexOf(value) > -1);
    this.setState({ result: newList });
  };

  handleSubmit = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      extraItemList: { addExtraItemList },
      location: { query },
    } = this.props;
    const { attachmentUrl } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      // fieldsValue.attachmentUrl
      fieldsValue.attachmentUrl = attachmentUrl ? attachmentUrl : fieldsValue.attachmentUrl;
      const params = {
        ...fieldsValue,
        storeFeatures: fieldsValue.storeFeatures ? fieldsValue.storeFeatures.join(',') : '',
        extraItemDetailList: [...addExtraItemList],
      };

      params.id = query ? query.id : '';
      dispatch({
        type:
          (query ? query.type : '') === 'edit'
            ? 'extraItemList/doExtraItemEdit'
            : 'extraItemList/doAddExtraItemList',
        payload: params,
        callback: res => {
          if (res.success) {
            if (res.success) {
              let secondsToGo = 3;
              const modal = Modal.success({
                title: (query ? query.type : '') === 'edit' ? '修改成功' : '新增成功',
                content: `将在${secondsToGo}秒后返回套餐加项列表页面`,
                okText: '知道了',
              });
              const timer = setInterval(() => {
                secondsToGo -= 1;
                modal.update({
                  content: `将在${secondsToGo}秒后返返回套餐加项列表页面`,
                });
              }, 1000);
              setTimeout(() => {
                clearInterval(timer);
                modal.destroy();
                dispatch(routerRedux.push('/Enterprise/extraItem-list'));
              }, secondsToGo * 1000);
            } else {
              message.info(res.errorDesc);
            }
          } else {
            message.info(res.errorDesc);
          }
        },
      });
    });
  };

  handleAdd = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'extraItemList/addExtraItemList',
    });
  };

  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  // 查询门店
  handleSearchForm = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'dict/dictStoreList',
        payload: { ...fieldsValue },
      });
    });
  };

  // handleInputChange = (e, r, n) => {
  //   let value = '';
  //   if (typeof e === 'string') {
  //     value = e;
  //   } else {
  //     value = e.target.value;
  //   }
  //   const { dispatch } = this.props;
  //
  //   const { key } = r;
  //   const newobj = { ...r };
  //   newobj[n] = value;
  // 	console.log(1);
  //   dispatch({
  //     type: 'extraItem/addExtraItemList',
  //     payload: newobj,
  //   });
  // };
  //

  handleDelete = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'extraItemList/deleteExtraItemList',
      payload: { key: record.key },
    });
  };

  handleCancel = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/Enterprise/extraItem-list'));
  };

  renderOptionsC = () => {
    const {
      dict: { cityList },
    } = this.props;
    const options = cityList.map(v => <Option value={v.id}>{v.name}</Option>);
    return options;
  };

  renderOptionsP = () => {
    const {
      dict: { provinceList },
    } = this.props;
    const options = provinceList.map(v => <Option value={v.id}>{v.name}</Option>);
    return options;
  };

  renderOptionsPosition = () => {
    const {
      enterpriseList: { positionList },
    } = this.props;
    const options = positionList.map(v => <Option value={v.id}>{v.name}</Option>);
    return options;
  };

  renderOptionsH = () => {
    const {
      contractList: { list },
    } = this.props;
    const options = list.map(v => <Option value={v.id}>{v.title}</Option>);
    return options;
  };

  renderExtraItemIds = d => {
    const newList = d.map(value => {
      const v = value;
      return <Option value={v.id}>{v.name}</Option>;
    });

    return newList;
  };

  renderInstitutionId = d => {
    const newList = d.map(value => {
      const v = value;
      return <Option value={v.id}>{v.name}</Option>;
    });

    return newList;
  };

  renderStoreFeatures = d => {
    const newList = d.map(value => {
      const v = value;
      return <Option value={v.id}>{v.dictValue}</Option>;
    });

    return newList;
  };

  handleInputChange = (e, r, n) => {
    let value = '';
    if (typeof e === 'string') {
      value = e;
    } else {
      value = e.target.value;
    }
    const { dispatch } = this.props;

    const newobj = { ...r };
    newobj[n] = value;
    dispatch({
      type: 'extraItemList/editExtraItemList',
      payload: newobj,
    });
  };

  render() {
    const {
      loading,
      form,
      extraItemList: { extraItemList, addExtraItemList, detailData },
      dict: { dictList },
      institutionList: { dictInstitutionList },
    } = this.props;

    const { result, contarctValue, imageUrl, stateLoading, type } = this.state;
    const { getFieldDecorator } = form;

    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        render: (v, r) =>
          r.type === 'add' || r.type === 'edit' ? (
            <Input defaultValue={v} onChange={e => this.handleInputChange(e, r, 'name')} />
          ) : (
            <span>{v}</span>
          ),
      },
      {
        title: '价格',
        dataIndex: 'price',
        render: (v, r) =>
          r.type === 'add' || r.type === 'edit' ? (
            <Input defaultValue={v} onChange={e => this.handleInputChange(e, r, 'price')} />
          ) : (
            <span>{v}</span>
          ),
      },
      {
        title: '描述',
        dataIndex: 'description',
        render: (v, r) =>
          r.type === 'add' || r.type === 'edit' ? (
            <Input defaultValue={v} onChange={e => this.handleInputChange(e, r, 'description')} />
          ) : (
            <span>{v}</span>
          ),
      },
      {
        title: '操作',
        render: (val, record) => (
          <div>
            <a onClick={() => this.handleDelete(record)}>删除</a>
          </div>
        ),
      },
    ];

    const uploadButton = (
      <div>
        <Icon type={loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">上传图片</div>
      </div>
    );

    const detailInfo = type == 'add' ? {} : detailData;

    return (
      <PageHeaderLayout>
        <Card bordered={false} style={{ paddingBottom: '20px' }} loading={loading}>
          <Alert message="套餐加项信息" type="info" />
          <Form layout="inline">
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="企业名称&#12288;">
                  {getFieldDecorator('companyId', {
                    initialValue: detailInfo?.companyId,
                    rules: [{ required: true, message: '请输入企业名称' }],
                  })(
                    <Select
                      showSearch
                      placeholder="输入企业名称查询"
                      style={{ width: 150 }}
                      optionFilterProp="children"
                      onChange={this.onSelect}
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {result}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="合同名称">
                  {getFieldDecorator('contractId', {
                    initialValue: detailInfo?.contractId,
                    rules: [{ required: true, message: '请选择合同名称' }],
                  })(
                    <Select
                      placeholder="请选择"
                      style={{ width: 150 }}
                      onChange={this.onChangeH}
                      autoClearSearchValue
                      allowClear
                      value={contarctValue}
                    >
                      {this.renderOptionsH()}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="加项包名称">
                  {getFieldDecorator('name', {
                    initialValue: detailInfo?.name,
                    rules: [{ required: true, message: '请输入套餐名称' }],
                  })(<Input />)}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="价格&#12288;&#12288;">
                  {getFieldDecorator('price', {
                    initialValue: detailInfo?.price,
                    rules: [{ required: true, message: '请选择职务' }],
                  })(<Input />)}
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col md={12} sm={24}>
                <FormItem label="加项包描述">
                  {getFieldDecorator('description', {
                    initialValue: detailInfo?.description,
                    rules: [{ required: true, message: '请输入加项包描述' }],
                  })(<Input par />)}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="&#12288;门店特性">
                  {getFieldDecorator('storeFeatures', {
                    initialValue: !detailInfo.storeFeatures ? undefined : detailInfo.storeFeatures,
                  })(
                    <Select mode="multiple" style={{ width: 300 }} placeholder="请选择">
                      {this.renderStoreFeatures(dictList)}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="是否可用积分抵扣">
                  {getFieldDecorator('canUsePoints', {
                    initialValue: detailInfo?.canUsePoints,
                    rules: [{ required: true, message: '请选择是否可用积分抵扣' }],
                  })(
                    <Select placeholder="请选择" style={{ width: 150 }}>
                      <Option key={1}>是</Option>
                      <Option key={2}>否</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>

            { /* <Row>
              <Col md={6} sm={24}>
                <FormItem label="可选设置&#12288;">
                  {getFieldDecorator('chooseType', {
                    initialValue: detailInfo?.chooseType,
                    rules: [{ required: true, message: '请选择可选设置' }],
                  })(
                    <Select placeholder="请选择" style={{ width: 88 }}>
                      <Option key={0}>无设置</Option>
                      <Option key={1}>必须</Option>
                      <Option key={2}>仅选</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col md={6} sm={24}>
                <FormItem label="数量">
                  {getFieldDecorator('chooseNum', {
                    initialValue: detailInfo?.chooseNum,
                  })(<InputNumber />)}
                </FormItem>
              </Col>
              <Col md={6} sm={24}>
                <FormItem label="免费数量">
                  {getFieldDecorator('freeNum', {
                    initialValue: detailInfo?.freeNum,
                  })(<InputNumber />)}
                </FormItem>
              </Col>
            </Row> */}

            <Row>
              <Col md={24} sm={24}>
                <FormItem label="加项包详情">
                  {getFieldDecorator('attachmentUrl', {
                    initialValue: detailInfo?.attachmentUrl,
                    rules: [{ required: true, message: '请输入套餐详情' }],
                  })(
                    <Upload {...this.uploadProps}>
                      {detailInfo?.attachmentUrl ? (
                        <img src={detailInfo?.attachmentUrl} alt="file" style={{ width: '100%' }} />
                      ) : imageUrl ? (
                        <img src={imageUrl} alt="file" style={{ width: '100%' }} />
                      ) : (
                        uploadButton
                      )}
                    </Upload>
                  )}
                </FormItem>
              </Col>
            </Row>
          </Form>
          {/*
          <Alert message="套餐加项明细" type="info" />
          <div style={{ margin: '10px 0' }}>
            <Button type="primary" icon="plus" onClick={this.handleAdd}>
              新增
            </Button>
          </div>

          <SimpleTable
            selectedRows={false}
            onSelectRow={false}
            loading={loading}
            data={{ list: addExtraItemList }}
            columns={columns}
            onChange=""
            rowKey="key"
          />
					*/}
        </Card>
        <div style={{ textAlign: 'center' }}>
          <Button type="primary" style={{ marginRight: 20 }} onClick={this.handleSubmit}>
            提交
          </Button>
          <Button type="" onClick={this.handleCancel}>
            返回
          </Button>
        </div>
      </PageHeaderLayout>
    );
  }
}
